package org.redis.cluster.extension.helper;

import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.redis.cluster.util.ClassUtil;
import org.redis.cluster.util.PropertiesUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ExtensionLoaderHelper {
	
	protected final static Logger logger=LoggerFactory.getLogger(ExtensionLoaderHelper.class);

	/**
	 * 读取
	 * @param url
	 * @return
	 * @throws IOException
	 */
	public static Map<String,Class<?>> read(URL url) throws IOException,ClassNotFoundException {
		Properties properties=PropertiesUtil.read(url.openStream());
		if(properties.isEmpty()) {
			return MapUtils.EMPTY_MAP;
		}
		
		Map<String,Class<?>> result=new HashMap<String,Class<?>>();
		for(Object key:properties.keySet()) {
			Object value=properties.get(key);
			
			String name=key.toString();
			String className=value.toString();
			
			if(StringUtils.isBlank(name) || StringUtils.isBlank(className)) {
				continue;
			}
			
			Class<?> clazz=null;
			try {
				if(logger.isDebugEnabled()) {
					logger.debug("准备读取扩展 - {} - {}",name,className);
				}
				clazz=ClassUtil.forName(className);
			}
			catch(ClassNotFoundException e) {
				throw new ClassNotFoundException(url.toString()+" - "+name+" 类不存在",e);
			}
			
			result.put(name, clazz);
		}
		return result;
	}
}